/**
 * 
 */
package com.android.dwt.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.IBinder;
import android.util.Log;
import android.widget.DatePicker;

import com.android.dwt.TaskItem;
import com.android.dwt.data.GTDApp;
import com.android.dwt.fragment.TodayFrag;
import com.android.dwt.service.DWTService;
import com.android.dwt.service.DWTService.MyBinder;
import com.android.dwt.ui.DayView;
import com.android.dwt.ui.MainAct;
import com.android.dwt.ui.NewTaskAct;
import com.android.dwt.ui.ViewTaskAct;

/**
 * @author xiang
 *
 */
public class TaskUtil {
	
	private static final String TAG = "TaskUtil";
	
	public static SimpleDateFormat mSdfDate = new SimpleDateFormat("yyyy-MM-dd");
	public static SimpleDateFormat mSdfTime = new SimpleDateFormat("HH:mm");
	public static SimpleDateFormat mSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

	
	public static int getListIndex(String[] array, String list) {
		
		int index = -1;
		
		for (int i=0; i<array.length; i++) {
			
			if (array[i].equals(list)) {
				
				index = i;
				break;
			}
			
		}
		
		if (index == -1) {
			
			Log.e(TAG, "the requested string is not found in this array!");
		}
		
		return index;
	}
	
	public static void editTask(final Context context, final int listIndex, final long rowId) {
		
		Log.e(TAG, "Activity local class name: " + ((Activity) context).getLocalClassName());
		Log.e(TAG, "editTask:  rowid " + rowId);
		
		Activity act = (Activity) context;
		
		final GTDApp ga = (GTDApp) context.getApplicationContext();
		TaskItem task = ga.getDbta().getTaskItem(rowId);
		
		Intent itt = new Intent(context, NewTaskAct.class);
		
		itt.putExtra("row_id", rowId);
//		itt.putExtra("task_data", task);
		itt.putExtra("list_index", listIndex);
//		itt.putExtra("selected_date", act.getIntent().getStringExtra("selected_date"));
		
		if (task.getListName().equals(ga.mList[GTDApp.AGENDA])) {
			
			itt.putExtra("selected_date", task.getStartTime());
		}
		
		act.startActivityForResult(itt, 0);
		
		if (ga.mFinishAct) {
			
			ga.mFinishAct = false;
			act.finish();
		}
		
	}
	
	public static void removeTask(final Context context, final int listIndex, final long rowId) {
		
		final Activity act = (Activity) context;
		
		final GTDApp ga = (GTDApp) context.getApplicationContext();
		
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("确定要删除该任务吗");
		
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
				TaskItem task = ga.getDbta().getTaskItem(rowId);
				task.setCompletedStatus(C.TASK.CANCELLED);
				ga.getDbta().updateTask(rowId, task);
				
				if (ga.mRefresh) {
					
					ga.mRefresh = false;
					
					String name = act.getLocalClassName();
					
					Log.e(TAG, "package name: " + act.getPackageName());
					Log.e(TAG, "local class name: " + name);
					
					if (name.equals("ui.ViewTaskAct")) {
						
						((ViewTaskAct) act).updateAdapterData();
						
					} else if (name.equals("ui.MainAct")) {
						
//						((TodayAct) act).updateAdapterView();
						((TodayFrag) ((MainAct) act).getFragments().get(MainAct.TODAY))
							.updateAdapterView();
						
					} else if (name.equals("ui.DayView")) {
						
						((DayView) act).updateAdapterView();
						
					} else {
						
						;
					}
					
				}
				
				String remind = task.getRemind();
				String loc = task.getPosition();
				
				final boolean timeRemind = remind.length()>0 ? true : false;
				final boolean locAlert = (loc.equals(ga.getPositions().get(0).getPlace())) ? false : true;
				
				// remove alarm of this task if there is.
				if (timeRemind || (ga.mPosRemind && locAlert)) {
					
    				// bind service 
    				Intent i = new Intent(context, DWTService.class);
    				context.bindService(i, new ServiceConnection() {
    	    			
    	    			@Override
    	    			public void onServiceDisconnected(ComponentName name) {
    	    				// TODO Auto-generated method stub
    	    				
    	    			}
    	    			
    	    			@Override
    	    			public void onServiceConnected(ComponentName name, IBinder service) {
    	    				// TODO Auto-generated method stub
    	    				
    	    				MyBinder binder = (MyBinder) service;
    	    		        DWTService svc = binder.getService();
    	    		        
    	    		        Log.e(TAG, "now will remove alarm of task: " + rowId);
    	    		        
    	    		        if (timeRemind) {
    	    		        	
    	    		        	svc.removeSingleAlarm(rowId);
    	    		        }
    	    		        
    	    		        if (ga.mPosRemind && locAlert) {
    	    		        	
    	    		        	svc.removeLocAlert(rowId);
    	    		        }
    	    		        
    	    		        context.unbindService(this);
    	    			}
    	    			
    	    		}, Context.BIND_AUTO_CREATE);
				
				}
				
				SharedPreferences prefs = context.getSharedPreferences(GTDApp.strList, GTDApp.MODE);
				Editor editor = prefs.edit();
				
				if (listIndex != -1) {
					
    				// update the counter
    				int count = (Integer) ga.lists.get(listIndex).get("item_count");
    				ga.lists.get(listIndex).put("item_count", count-1);
    				
    				editor.putInt("List_count["+listIndex+"]", count-1);
				}
				
				editor.commit();
				
				dialog.dismiss();
				
				if (ga.mFinishAct) {
					
					ga.mFinishAct = false;
					act.finish();
				}
				
			}
			
		});
		
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		
		builder.show();
	}
	
	public static void moveTask(final Context context, final int listIndex, final long rowId) {
		
		final Activity act = (Activity) context;
		
		final GTDApp ga = (GTDApp) context.getApplicationContext();
		final Calendar selectDay = Calendar.getInstance();
		
		/*ArrayList<String> als = new ArrayList<String>();
		ArrayList<ListItem> al = ga.getListItems();
		
		for (int i=0; i<al.size(); i++) {
			
			als.add(al.get(i).getListName());
		}*/
		
//		final String[] items = (String[]) als.toArray(new String[als.size()]);
		final String[] items = ga.mList;
		
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		
		builder.setTitle("移动到");
		
		builder.setSingleChoiceItems(items, listIndex,
				new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(final DialogInterface dialog, final int item) {
				
				// TODO Auto-generated method stub
				if (item != listIndex) {
					
					final TaskItem task = ga.getDbta().getTaskItem(rowId);
					task.setListName(items[item]);
					task.setCompletedStatus(C.TASK.UNCOMPLETED);
					
					ga.getDbta().updateTask(rowId, task);
					if (ga.mRefresh) {
						
						ga.mRefresh = false;
						
						String name = act.getLocalClassName();
						if (name.equals("ui.ViewTaskAct")) {
							
							((ViewTaskAct) act).updateAdapterData();
							
						} else if (name.equals("ui.MainAct")) {
							
//							((TodayAct) act).updateAdapterView();
							((TodayFrag) ((MainAct) act).getFragments().get(MainAct.TODAY))
								.updateAdapterView();
							
						} else if (name.equals("ui.DayView")) {
							
							((DayView) act).updateAdapterView();
							
						} else {
							
							;
						}
						
					}
					
					if (item == GTDApp.AGENDA) {	// move a non-agenda task to agenda task
						
						OnDateSetListener dateListener = new OnDateSetListener() {
							
							@Override
							public void onDateSet(DatePicker view, int year, int monthOfYear,
									int dayOfMonth) {
								
//								Log.e(TAG, "onDateSet: "+year+" "+monthOfYear+" "+dayOfMonth);
								
								// TODO Auto-generated method stub
								selectDay.set(year, monthOfYear, dayOfMonth, 0, 0);
								
								task.setAllDay(true);		// all day task
								task.setStartTime(mSdf.format(selectDay.getTime()));
								task.setEndTime(mSdf.format(selectDay.getTime()));
								task.setRepeat("");	// no repeat
								
								task.setListName(items[item]);
								ga.getDbta().updateTask(rowId, task);
								
								SharedPreferences prefs = context.getSharedPreferences(GTDApp.strList, GTDApp.MODE);
								Editor editor = prefs.edit();
								
								if (listIndex != -1) {
									
    								// update the counter
    								int count1 = (Integer) ga.lists.get(listIndex).get("item_count");
    								ga.lists.get(listIndex).put("item_count", count1-1);
    								
    								editor.putInt("List_count["+listIndex+"]", count1-1);
								}
								
								int count2 = (Integer) ga.lists.get(item).get("item_count");
								ga.lists.get(item).put("item_count", count2+1);
								
								editor.putInt("List_count["+item+"]", count2+1);
								editor.commit();
								
								dialog.dismiss();
								
								if (ga.mFinishAct) {
									
									ga.mFinishAct = false;
									((Activity) context).finish();
								}
								
							}
							
						};
						
						DatePickerDialog dateDlg = new DatePickerDialog(
								context,
		                        dateListener,
		                        selectDay.get(Calendar.YEAR),
								selectDay.get(Calendar.MONTH),
								selectDay.get(Calendar.DAY_OF_MONTH));
						
						dateDlg.setOnDismissListener(new OnDismissListener() {
							
							@Override
							public void onDismiss(DialogInterface dialog) {
								// TODO Auto-generated method stub
								
//								Log.e(TAG, "DatePickerDialog is dismissed!");
								
								dialog.dismiss();
							}
							
						});
						
						dateDlg.show();
						
					} else {		// move to a non-agenda task
						
						SharedPreferences prefs = context.getSharedPreferences(GTDApp.strList, GTDApp.MODE);
						Editor editor = prefs.edit();
						
//						task.setListName(items[item]);
//						ga.getDbta().updateTask(rowId, task);
						
						// update the counter
						if (listIndex != -1) {
							
							int count1 = (Integer) ga.lists.get(listIndex).get("item_count");
							ga.lists.get(listIndex).put("item_count", count1-1);
							
							editor.putInt("List_count["+listIndex+"]", count1-1);
						}
						
						int count2 = (Integer) ga.lists.get(item).get("item_count");
						ga.lists.get(item).put("item_count", count2+1);
						
						editor.putInt("List_count["+item+"]", count2+1);
						editor.commit();
						
						dialog.dismiss();
						
						if (ga.mFinishAct) {
							
							ga.mFinishAct = false;
							act.finish();
						}
						
					}
					
				} else {
				
					dialog.dismiss();
				}
				
			}
			
		});
		
		builder.show();
	}
	
}
